package com.katze.boot.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.katze.boot.system.dao.RoleMenuMapper;
import com.katze.boot.system.domain.Role;
import com.katze.boot.system.domain.RoleMenu;
import com.katze.boot.system.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service("roleMenuService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

	@Override
	public void save(Role role) {
		if (role.getMenus() != null){
			List<RoleMenu> list = role.getMenus().stream().map(item -> new RoleMenu(role.getRoleId(), item.getMenuId())).collect(Collectors.toList());
			saveBatch(list);
		}
	}

	@Override
	public Function<Function<Long[], List<String>>, List<String>> resetRoleMenus(Role role) {
		return (fun) -> {
			int count = this.baseMapper.delete(Wrappers.lambdaQuery(RoleMenu.class).eq(RoleMenu::getRoleId, role.getRoleId()));
			this.save(role);
			if (count > 0) {
				return fun.apply(new Long[]{role.getRoleId()});
			} else {
				return new ArrayList<>();
			}
		};
	}

	@Override
	@Transactional
	public void deleteRoleMenusByRoleId(Object[] roleIds) {
		baseMapper.delete(Wrappers.lambdaQuery(RoleMenu.class).in(RoleMenu::getRoleId, roleIds));
	}

	@Override
	@Transactional
	public void deleteRoleMenusByMenuId(Object[] menuIds) {
		baseMapper.delete(Wrappers.lambdaQuery(RoleMenu.class).in(RoleMenu::getMenuId, menuIds));
	}

	@Override
	public Set<String> getRoleMenusByRoleId(Object[] roleIds) {
		if (roleIds.length == 0) return new HashSet<>();
		List<RoleMenu> list = baseMapper.selectList(Wrappers.lambdaQuery(RoleMenu.class).in(RoleMenu::getRoleId, roleIds));
		return list != null ?list.stream().map(RoleMenu::getMenuId).collect(Collectors.toSet()):new HashSet<>();
	}

}
